package com.ruoyi.gateway.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.gateway.domain.DeviceMap;
import com.ruoyi.gateway.domain.dto.MessageTransformResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

@Service
public class MessageTransformService {

    @Autowired
    private IMessagePropertyMapService propertyService;

    public MessageTransformResult deviceToPlatform(byte[] deviceMessage, DeviceMap mapping) {
        try {
            String deviceMsgStr = new String(deviceMessage, StandardCharsets.UTF_8);
            JSONObject deviceJson = JSON.parseObject(deviceMsgStr);

            JSONObject platformJson = new JSONObject();

            // 转换属性
            if (deviceJson.containsKey("states")) {
                JSONObject properties = new JSONObject();
                JSONObject deviceStates = deviceJson.getJSONObject("states");

                for (String deviceKey : deviceStates.keySet()) {
                    String platformKey = propertyService.getPlatformProperty("up", deviceKey);
                    if (platformKey != null) {
                        properties.put(platformKey, deviceStates.get(deviceKey));
                    }
                }

                platformJson.put("properties", properties);
            }

            // 添加序列号
            platformJson.put("serialNumber", mapping.getPlatformDeviceSerialNumber());

            return new MessageTransformResult(platformJson.toJSONString().getBytes(), deviceMessage);

        } catch (Exception e) {
            throw new RuntimeException("消息转换失败", e);
        }
    }

    public MessageTransformResult platformToDevice(byte[] platformMessage, DeviceMap mapping) {
        try {
            String platformMsgStr = new String(platformMessage, StandardCharsets.UTF_8);
            JSONObject platformJson = JSON.parseObject(platformMsgStr);

            JSONObject deviceJson = new JSONObject();
            deviceJson.put("class", "display");
            deviceJson.put("index", mapping.getClientDeviceIndex());

            if (platformJson.containsKey("properties")) {
                JSONObject states = new JSONObject();
                JSONObject platformProperties = platformJson.getJSONObject("properties");

                for (String platformKey : platformProperties.keySet()) {
                    String deviceKey = propertyService.getDeviceProperty("down", platformKey);
                    if (deviceKey != null) {
                        states.put(deviceKey, platformProperties.get(platformKey));
                    }
                }

                deviceJson.put("states", states);
            }

            return new MessageTransformResult(platformMessage, deviceJson.toJSONString().getBytes());

        } catch (Exception e) {
            throw new RuntimeException("消息转换失败", e);
        }
    }
}
